package SwordOffer2;

public class day7_1 {
    /*
     * 1.创建res，res1指向head，计算链表长度count
     * 2.计算要删除的链表节点位置k=count-n
     * 3.再次循环链表当head到k的位置时，删除节点，返回链表指针res1
     * */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode res = head;
        ListNode res1 = res;
        int count = 0;
        while (head != null) {
            head = head.next;
            count++;
        }
        //System.out.println(count);
        int k = count - n;
        if (k == 0) {
            res = res.next;
            return res;
        }
        int count1 = 0;
        while (res != null) {
            count1++;
            if (count1 == k) {
                res.next = res.next.next;
                break;
            }
            res = res.next;
        }
        return res1;
    }
}
